﻿using General.Entities.Models;
using General.Framework;
using General.Framework.Admin;
using General.Mvc.Filters;
using General.Services.Admin;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Controllers.Admin.Public
{
    /// <summary>
    ///上传控制器
    /// </summary>
    [Route("api/admin/Public/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class UploadController : Controller
    {
        private readonly IAdminService adminService;
        private readonly ILogger<UploadController> logger;

        public UploadController(IAdminService adminService,
            ILogger<UploadController> logger)
        {
            this.adminService = adminService;
            this.logger = logger;
        }

        #region 文件管理

        /// <summary>
        /// 上传Base64图片
        /// </summary>
        /// <param name="fileBase64"></param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> UploadBase64([FromServices] IWebHostEnvironment environment, [FromForm] string fileBase64,[FromForm]int isSelf=1)
        {
            AjaxResult result = new AjaxResult();
            string path = string.Empty;
            byte[] bytes = Convert.FromBase64String(fileBase64);
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            string newFileName = System.Guid.NewGuid().ToString() + ".png"; //随机生成新的文件名
            var filePath = webRootPath + "/upload/" + timedir;
            var RetfilePath = "upload/" + timedir + newFileName;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = webRootPath + "/upload/" + timedir + newFileName;
            try
            {
                result.code = AjaxResultStateEnum.Ok;
                FileStream fs = new FileStream(filePath, FileMode.CreateNew);
                await fs.WriteAsync(bytes, 0, bytes.Length);
                fs.Close();
                result.message = "/" + RetfilePath;
                if (isSelf == 1)
                {
                    var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
                    await adminService.UpdateHeadImg(user.id, result.message);
                }
                
            }
            catch (Exception ex)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "上传失败!";
                logger.LogInformation(new Exception("UploadBase64上传失败"), ex.Message);
            }
            return Content(JsonHelper.Serialize(result));
        }




        /// <summary>
        /// 弹窗选择文件上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        [RequestSizeLimit(5000_000_000)] //最大5000m
        public async Task<IActionResult> UploadFile2([FromServices] IWebHostEnvironment environment, string resultType)
        {
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { return Json(new { code = 0, msg = "请选择上传的文件." }); }
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = "/" + DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            if (!Directory.Exists(webRootPath + "/upload" + timedir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + timedir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload" + timedir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }

            string strpath = Path.Combine("upload" + timedir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }

            if (resultType == "tinymce")
            {
                return Json(new { location = "/" + strpath });
            }

            return Json(new { code = 200, msg = "上传成功!" });
        }

        /// <summary>
        /// 文件上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        [RequestSizeLimit(5000_000_000)] //最大5000m
        public async Task<IActionResult> UploadFile([FromServices] IWebHostEnvironment environment, [FromForm] string dir = "/")
        {
            AjaxResult state = new AjaxResult();
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { state.code = 0; state.message = "请选择上传的文件。"; return Json(state); }
            string webRootPath = environment.WebRootPath;

            if (!Directory.Exists(webRootPath + "/upload" + dir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + dir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload" + dir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }

            string strpath = Path.Combine("upload" + dir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }


            state.code = AjaxResultStateEnum.Ok;
            state.message = "上传成功";
            return Json(state);
        }

        #endregion

    }
}
